<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>14.利用闭包根据字段排序商品</title>
</head>

<body>
  <script>
    let lessons = [
      {
        title: "媒体查询响应式布局",
        click: 89,
        price: 12
      },
      {
        title: "FLEX 弹性盒模型",
        click: 45,
        price: 120
      },
      {
        title: "GRID 栅格系统",
        click: 19,
        price: 67
      },
      {
        title: "盒子模型详解",
        click: 29,
        price: 300
      }
    ];
    /*
    伪代码
    lessons = {
      sort: function(callback) {
        callback(a,b)
      }
    }
    */
    function order (field, type = "asc") {
      return function (a, b) {
        // 内存中开辟新的环境
        // 闭包原理，可以访问 field和type变量
        // 父作用域的两个变量不会改变
        //升序
        if (type === 'asc')
          return a[field] > b[field] ? 1 : -1;
        // 降序 
        else
          return a[field] > b[field] ? -1 : 1;

      };
    }
    console.table(lessons.sort(order("click","desc")));
  </script>
</body>

</html>